package com.pw.study.flink.sql;

import com.pw.study.flink.entities.WaterSensor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.table.functions.TableAggregateFunction;
import org.apache.flink.util.Collector;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * @Author: linux_future
 * @since: 2022/3/12
 **/
public class $16FunAgg {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);

        DataStreamSource<WaterSensor> waterSensorStream =
                env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                        new WaterSensor("sensor_1", 2000L, 20),
                        new WaterSensor("sensor_2", 3000L, 30),
                        new WaterSensor("sensor_1", 4000L, 40),
                        new WaterSensor("sensor_1", 5000L, 50),
                        new WaterSensor("sensor_2", 6000L, 60));

        Table table = tEnv.fromDataStream(waterSensorStream);
        mc1(table);
        mc2(tEnv, table);
        mcSql1(tEnv, table);

        mk1(table);
        mk2(tEnv, table);

    }

    private static void mk2(StreamTableEnvironment tEnv, Table table) {
        System.out.println("============4.注册后使用==============");
        tEnv.createTemporaryFunction("top2", Top2.class);
        table.groupBy($("id")).flatAggregate(call("top2", $("vc")).as("v", "rank"))
                .select($("id"), $("v"), $("rank")).execute().print();
    }

    private static void mk1(Table table) {
        System.out.println("==============top2内联使用==============");
        table.groupBy($("id")).flatAggregate(call(Top2.class, $("vc")).as("v", "rank"))
                .select($("id"), $("v"), $("rank")).execute().print();
    }

    private static void mcSql1(StreamTableEnvironment tEnv, Table table) {
        System.out.println("=====3.sql=========");
        tEnv.createTemporaryView("tb_sensor", table);
        tEnv.createTemporaryFunction("myAvg", VcAvg.class);
        tEnv.sqlQuery("select id,myAvg(vc) from tb_sensor group by id").execute().print();

    }

    private static void mc2(StreamTableEnvironment tEnv, Table table) {
        System.out.println("2.注册方法。。。。。");
        tEnv.createTemporaryFunction("avg", VcAvg.class);
        table.groupBy($("id")).select($("id"), call("avg", $("vc")).as("avg1")).execute().print();

    }

    private static void mc1(Table table) {
        System.out.println("1.table......");
        table.groupBy($("id")).select($("id"), call(VcAvg.class, $("vc")).as("avg2")).execute().print();
    }

    public static class VCAcc {
        public Integer sum = 0;
        public Long count = 0L;

    }

    public static class VcAvg extends AggregateFunction<Double, VCAcc> {
        @Override
        public Double getValue(VCAcc accumulator) {
            return accumulator.sum * 1.0 / accumulator.count;
        }

        @Override
        public VCAcc createAccumulator() {
            return new VCAcc();
        }

        public void accumulate(VCAcc acc, Integer vc) {
            acc.sum += vc;
            acc.count += 1L;
        }


    }

    public static class Top2 extends TableAggregateFunction<Tuple2<Integer, Integer>, Top2Acc> {

        @Override
        public Top2Acc createAccumulator() {
            return new Top2Acc();
        }

        public void accumulate(Top2Acc acc, Integer vc) {
            if (vc > acc.first) {
                acc.second = acc.first;
                acc.first = vc;
            } else if (vc > acc.second) {
                acc.second = vc;
            }
        }

        public void emitValue(Top2Acc acc, Collector<Tuple2<Integer, Integer>> out) {
            if (acc.first != Integer.MIN_VALUE) {
                out.collect(Tuple2.of(acc.first, 1));
            }

            if (acc.second != Integer.MIN_VALUE) {
                out.collect(Tuple2.of(acc.second, 2));
            }

        }

    }

    public static class Top2Acc {
        public Integer first = Integer.MIN_VALUE; // top 1
        public Integer second = Integer.MIN_VALUE; // top 2

    }
}
